package org.cbyyx.tc.aop;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.cbyyx.tc.annotation.AuthCheck;
import org.cbyyx.tc.constant.UserConstant;
import org.cbyyx.tc.enums.ErrorCode;
import org.cbyyx.tc.exception.BusinessException;
import org.cbyyx.tc.model.vo.userResponse.UserVO;
import org.cbyyx.tc.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class AuthAspect {

    private final UserService userService;

    @Around("@annotation(authCheck)")
    public Object checkAuth(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        // 获取当前登录用户
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String mustRole = authCheck.role();
        HttpSession session = request.getSession();
        // 检查是否登录以及数据是否正确
        UserVO userVO = userService.getCurrentUser(session);
        if (userVO == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"请登录");
        }
        log.info("权限认证:{}",userVO);
        String userRole = userVO.getRole();
        // 检查权限
        if (userRole == null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"没有权限");
        }
        if (userRole.equals(UserConstant.BAN)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"已被封禁");
        }
        //管理员和用户权限直接放行
        if (mustRole.equals(UserConstant.USER) || userRole.equals(UserConstant.ADMIN)){
            return joinPoint.proceed();
        }
        //判断用户角色是否满足要求
        if (!userRole.equals(mustRole)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"没有权限");
        }
        return joinPoint.proceed();
    }
}